// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV});
const https = require("https");
const CustomError = require("./CustomError");

// 云函数入口函数
exports.main = async (event = {}, context) => {
    switch (event.actionName) {
        case "uploadFile": //上传文件
            return await uploadFile(event);
        case "deleteFile": //删除文件
            return await deleteFile(event);
        case "imgSecCheck": //图片合法验证
            return await imgSecCheck(event);
    }
}

/*
* 上传
* */
async function uploadFile(event) {
    try {
        let {file, path} = event.params
        let {OPENID} = cloud.getWXContext();
        let buffer = new Buffer(file, "base64");
        await cloud.openapi.security.imgSecCheck({
            media: {
                contentType: "image/jpg",
                value: buffer
            }
        })
        let res = await cloud.uploadFile({
            cloudPath: path + OPENID + "/" + new Date().getTime() + parseInt(10000 * Math.random()) + ".jpg",
            fileContent: buffer
        })
        return {status: 0, data: res.data};
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}
/*删除图片*/
async function deleteFile(event) {
    try {
        let {list} = event.params;
        let res = await cloud.deleteFile({
            fileList: list
        })
        return {status: 0, data: res.data};
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 文件合法性校验
* */
async function imgSecCheck(event) {
    try {
        let {cloudId} = event.params
        const result = await cloud.getTempFileURL({
            fileList: [cloudId]
        })
        const currentData = result.fileList[0];
        return await _checked(cloudId, currentData.tempFileURL)
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

async function _checked(cloudId, url) {
    return new Promise(async function (resolve, reject) {
        https.get(url, function(res){
            let chunks = []; //用于保存网络请求不断加载传输的缓冲数据
            let size = 0;　　 //保存缓冲数据的总长度
            res.on("data", function(chunk){
                chunks.push(chunk);　 //在进行网络请求时，会不断接收到数据(数据不是一次性获取到的)，
                size += chunk.length;　　//累加缓冲数据的长度
            });
            res.on("end", async function (err){
                try {
                    if (err) {throw err}
                    let data = Buffer.concat(chunks, size);　　//Buffer.concat将chunks数组中的缓冲数据拼接起来，返回一个新的Buffer对象赋值给data
                    await cloud.openapi.security.imgSecCheck({
                        media: {contentType: "image/jpg", value: data}
                    })
                    resolve({status: 0, data: {fileID: data.cloudId}})
                } catch (e) {
                    deleteFile({
                        actionName: "imgSecCheck",
                        list: [cloudId]
                    })
                    reject (e)
                }
            });
        });
    })
}
